package com.zcz.umengpush.util;

import com.zcz.umengpush.mapper.PushMsgMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;


public class PushClient {
	@Autowired
	private PushMsgMapper pushMsgMapper;
	public PushClient(){
		this.pushMsgMapper= SpringContextUtil.getBean(PushMsgMapper.class);
	}
	Logger logger = LoggerFactory.getLogger(getClass());
	// The user agent
	protected final String USER_AGENT = "Mozilla/5.0";

	// This object is used for sending the post request to Umeng
	//过时DefaultHttpClient()
	//protected HttpClient client = new DefaultHttpClient();
	CloseableHttpClient client = HttpClients.createDefault();
	
	// The host
	protected static final String host = "http://msg.umeng.com";
	
	// The upload path
	protected static final String uploadPath = "/upload";
	
	// The post path
	protected static final String postPath = "/api/send";

	public boolean send(UmengNotification msg,String ids) throws Exception {
		String timestamp = Integer.toString((int)(System.currentTimeMillis() / 1000));
		msg.setPredefinedKeyValue("timestamp", timestamp);
        String url = host + postPath;
        String postBody = msg.getPostBody();
        String sign = DigestUtils.md5Hex(("POST" + url + postBody + msg.getAppMasterSecret()).getBytes("utf8"));
        url = url + "?sign=" + sign;
        HttpPost post = new HttpPost(url);
        post.setHeader("User-Agent", USER_AGENT);
        StringEntity se = new StringEntity(postBody, "UTF-8");
        post.setEntity(se);
        // Send the post request and get the response  发送post请求并获得响应
        HttpResponse response = client.execute(post);
        int status = response.getStatusLine().getStatusCode();
        System.err.println("Response Code : " + status);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        System.err.println(result.toString());
        if (status == 200) {
            System.err.println("Notification sent successfully. 已经成功发送的通知");
            //修改发送状态
			//去掉第一个，号 并 字符串转数组
			String[] split = ids.substring(1).split(",");
				for (String id : split) {
					try {
						pushMsgMapper.updateSuccessPushMsg(id,new Date());
                       // logger.info("推送成功"+result.toString()+"消息的id="+id);
					} catch (Exception e) {
						e.printStackTrace();
						logger.error("参数错误");
					}finally {
						rd.close();
					}
			}
        } else {
            System.err.println("Failed to send the notification!未能发送通知");
            //修改发送次数和发送状态
			//去掉第一个，号 并 字符串转数组
			//List<String> asList = Arrays.asList(ids.substring(1));
			String[] asList = ids.substring(1).split(",");
			for (String id : asList) {
				try {
					pushMsgMapper.updateFailPushMsg(id);
                    //logger.info("发送成功"+result.toString()+"消息id="+id);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("参数错误,发送失败"+result.toString());
				}finally {
					rd.close();
				}
			}
        }
        return true;
    }
	public boolean send(UmengNotification msg) throws Exception {
		String timestamp = Integer.toString((int)(System.currentTimeMillis() / 1000));
		msg.setPredefinedKeyValue("timestamp", timestamp);
		String url = host + postPath;
		String postBody = msg.getPostBody();
		String sign = DigestUtils.md5Hex(("POST" + url + postBody + msg.getAppMasterSecret()).getBytes("utf8"));
		url = url + "?sign=" + sign;
		HttpPost post = new HttpPost(url);
		post.setHeader("User-Agent", USER_AGENT);
		StringEntity se = new StringEntity(postBody, "UTF-8");
		post.setEntity(se);
		// Send the post request and get the response  发送post请求并获得响应
		HttpResponse response = client.execute(post);
		int status = response.getStatusLine().getStatusCode();
		System.err.println("Response Code : " + status);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		System.out.println(result.toString());
		if (status == 200) {
			System.out.println("Notification sent successfully. 已经成功发送的通知");
		} else {
			System.out.println("Failed to send the notification!未能发送通知");
		}
		return true;
	}

	// Upload file with device_tokens to Umeng  上传带有设备令牌的文件到Umeng
	public String uploadContents(String appkey,String appMasterSecret,String contents) throws Exception {
		// Construct the json string
		JSONObject uploadJson = new JSONObject();
		uploadJson.put("appkey", appkey);
		String timestamp = Integer.toString((int)(System.currentTimeMillis() / 1000));
		uploadJson.put("timestamp", timestamp);
		uploadJson.put("content", contents);
		// Construct the request
		String url = host + uploadPath;
		String postBody = uploadJson.toString();
		String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes("utf8"));
		//System.err.println(sign);
		url = url + "?sign=" + sign;
		HttpPost post = new HttpPost(url);
		post.setHeader("User-Agent", USER_AGENT);
		StringEntity se = new StringEntity(postBody, "UTF-8");
		post.setEntity(se);
		// Send the post request and get the response
		HttpResponse response = client.execute(post);
		System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		System.out.println(result.toString());
		// Decode response string and get file_id from it
		JSONObject respJson = new JSONObject(result.toString());
		String ret = respJson.getString("ret");
		if (!ret.equals("SUCCESS")) {
			throw new Exception("Failed to upload file");
		}
		JSONObject data = respJson.getJSONObject("data");
		String fileId = data.getString("file_id");
		// Set file_id into rootJson using setPredefinedKeyValue
		
		return fileId;
	}

}
